/*
 * @Description: 主题配置
 * @Author: HuiSir<https://gitee.com/huisir001>
 * @Date: 2021-09-09 16:27:56
 * @LastEditTime: 2025-09-22 16:19:16
 */
import { defineStore } from "pinia";
import { reactive, toRefs } from "vue";
import { project } from "@/init/config";
import LocalCache from "@/utils/LocalCache";
import DomCreate from "@/utils/DomCreate";

/**
 * 动态导入主题文件
 */
const themeStyles = import.meta.glob("@/assets/styles/themes/**.scss");

/**
 * 初始化状态
 */
const {
  color: C_COLOR,
  showBreadcrumb: C_SHOW_BREAD_CRUMB,
  showLogo: C_SHOW_LOGO,
} = LocalCache.getCache(project.storage.theme) || {};

/**
 * state数据接口
 */
interface ThemeState extends Recordable {
  color?: string;
  showBreadcrumb?: boolean;
  showLogo?: boolean;
  linkEl: DomCreate;
}

export default defineStore("theme", () => {
  const state: ThemeState = reactive({
    /**
     * 主题配色
     */
    color: C_COLOR || project.theme.find((item) => item.default)!.name,
    /**
     * 面包屑显隐
     */
    showBreadcrumb:
      C_SHOW_BREAD_CRUMB === undefined ? true : C_SHOW_BREAD_CRUMB,
    /**
     * LOGO显隐
     */
    showLogo: C_SHOW_LOGO === undefined ? true : C_SHOW_LOGO,
    /**
     * 样式dom
     */
    linkEl: new DomCreate("style", { type: "text/css" }),
  });

  /**
   * 修改状态
   */
  const setStates = async (obj: Record<string, unknown>) => {
    // 主题色更改
    if (obj.color) {
      const themeStyle = (await themeStyles[
        project.theme.find((item) => item.name === obj.color)!.file
      ]()) as { default: string };

      const themeStyleStr = JSON.stringify(themeStyle.default).replace(
        /[",]/g,
        (e) => {
          return e === '"' ? "" : ";";
        }
      );

      state.linkEl.innerText(":root" + themeStyleStr);

      // 判断是否已经插入元素
      if (
        document.head.getElementsByClassName(state.linkEl.className).length ===
        0
      ) {
        document.head.append(state.linkEl.getElement() as HTMLElement);
      }
    }
    // 状态更新
    Object.keys(obj).forEach((key) => {
      state[key] = obj[key];
    });
    // 缓存
    const { color, showBreadcrumb, showLogo } = state;
    LocalCache.setCache(project.storage.theme, {
      color,
      showBreadcrumb,
      showLogo,
    });
  };

  return {
    ...toRefs(state),
    setStates,
  };
});
